var mongoose = require('mongoose');
var util = require('util');

mongoose.connect('mongobd://127.0.0.1/test');
util.puts("Mongoose Test 3");

var DeviceSchema = new mongoose.Schema({
	name : String,
	ports : [ {
		type : mongoose.Schema.ObjectId,
		ref : 'Port'
	} ]
});

var PortSchema = new mongoose.Schema({
	name : String,
	device : {
		type : mongoose.Schema.ObjectId,
		ref : 'Device'
	}
});

PortSchema.pre('save', function(next, done) {
	var self = this;
	util.puts("Port Pre-save");

	Device.findById(self.device, function(e, device) {
		util.puts("  Found Parent Device");
		device.ports.push(self);
		device.save(next);
		util.puts("  Saved Parent Device. DOne.");
	});
});

var Device = mongoose.model('Device', DeviceSchema);
var Port = mongoose.model('Port', PortSchema);

var d1 = new Device();
d1.name = "TestDevice";

d1.save(function(e) {
	util.puts("Saved Device");
	var p1 = new Port();
	p1.name = 'test1';
	p1.device = d1;
	p1.save(function(e) {
		util.puts("Saved New Port");
		//
		Device.find({}).populate('ports').run(function(e, devices) {
			devices.forEach(function(device) {
				util.puts(util.inspect(device) + "\r\n\r\n");
			});
		});
	});
});
